package com.acane.instagram.feature.me.player

import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.net.Uri
import android.view.ViewGroup
import android.widget.MediaController
import android.widget.VideoView
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.acane.instagram.core.config.Config
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun VideoPostPlayer(coverList: List<String>) {
    val context = LocalContext.current
    var playbackError by remember { mutableStateOf<String?>(null) }
    var showFullScreen by remember { mutableStateOf(false) }
    var thumbnailBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
    val coroutineScope = rememberCoroutineScope()

    LazyVerticalStaggeredGrid(
        columns = StaggeredGridCells.Fixed(3),
        modifier = Modifier.fillMaxSize()
    ) {
        items(coverList) { cover ->
            val videoUrl = "${Config.ADDRESS}video/$cover"

            // 生成缩略图
            LaunchedEffect(Unit) {
                coroutineScope.launch(Dispatchers.IO) {
                    try {
                        val retriever = MediaMetadataRetriever()
                        retriever.setDataSource(videoUrl, HashMap())
                        val bitmap = retriever.frameAtTime
                        bitmap?.let {
                            thumbnailBitmap = it.asImageBitmap()
                        }
                        retriever.release()
                    } catch (e: Exception) {
                        playbackError = "无法生成缩略图: ${e.message}"
                    }
                }
            }
            // 显示缩略图
            Box(modifier = Modifier.aspectRatio(1f)) {
                thumbnailBitmap?.let { bitmap ->
                    Image(
                        bitmap = bitmap,
                        contentDescription = "视频缩略图",
                        modifier = Modifier
                            .fillMaxSize()
                            .clickable { showFullScreen = true },
                        //.clip(RoundedCornerShape(16.dp)),
                        contentScale = ContentScale.Crop,
                    )
                }
            }


            // 全屏播放对话框
            if (showFullScreen) {
                Dialog(
                    onDismissRequest = { showFullScreen = false },
                    properties = DialogProperties(
                        usePlatformDefaultWidth = false,
                        decorFitsSystemWindows = false
                    )
                ) {
                    FullScreenVideoPlayer(
                        videoUrl = videoUrl,
                        onDismiss = { showFullScreen = false },
                        onError = { error -> playbackError = error }
                    )
                }
            }
            // 错误提示
            playbackError?.let { message ->
                Text(
                    text = message,
                    color = MaterialTheme.colorScheme.error,
                    modifier = Modifier.padding(8.dp)
                )
            }
        }
    }


}

@Composable
private fun FullScreenVideoPlayer(
    videoUrl: String,
    onDismiss: () -> Unit,
    onError: (String) -> Unit
) {
    val context = LocalContext.current

    AndroidView(
        factory = { androidContext ->
            VideoView(androidContext).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )

                setVideoURI(Uri.parse(videoUrl))
                setOnPreparedListener { mediaPlayer ->
                    // 设置循环播放
                    mediaPlayer.isLooping = true
                    // 居中显示视频
                    mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
                    start()
                }
                setMediaController(MediaController(context))
                setOnErrorListener { _, what, extra ->
                    onError("播放失败: 代码 $what, 附加信息 $extra")
                    false
                }
            }
        },
        modifier = Modifier
            .fillMaxSize()
            .clickable { onDismiss() }
    )
}